package org.example.company.filter;

import com.alibaba.fastjson.JSON;
import org.example.common.Constant;
import org.example.company.config.JwtProperties;
import org.example.company.utils.JwtTokenUtils;
import org.example.response.RespnseResult;
import org.example.response.ResultCode;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    private final JwtProperties jwtProperties;

    public TokenFilter(JwtProperties jwtProperties) {
        System.out.println("excute filter  construct-------------");
        this.jwtProperties = jwtProperties;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("excute filter-------------");
        ServerHttpRequest request=exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String token = request.getHeaders().getFirst(Constant.TOKEN);
        if (StringUtils.hasLength(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            Map<String, Object> stringObjectMap = JwtTokenUtils.verifyJwtWebToken(token, jwtProperties.getSecurityKey());
            if (stringObjectMap == null || !stringObjectMap.containsKey(Constant.TOKEN_USER_INFO)) {
                return getUnAuthorizedMono(response);
            }
            LinkedHashMap<String, Object> userDetials = (LinkedHashMap<String, Object>) stringObjectMap.get(Constant.TOKEN_USER_INFO);
            //使用 request.mutate() 方法创建一个可变的 ServerHttpRequest 对象，并添加一个名为 X-USER 的请求头，
            // 值为 userDetails.get("username")，即用户的用户名。
            ServerHttpRequest mutableReq = request.mutate().header(Constant.HEADER_USER, (String) userDetials.get(Constant.TOKEN_USER_INFO_USERNAME)).build();
            //使用 exchange.mutate() 方法创建一个新的 ServerWebExchange，并将修改后的 ServerHttpRequest 作为请求部分。
            ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();
            return chain.filter(mutableExchange);
        }
        return chain.filter(exchange);
    }

    //返回未经授权的响应
    private Mono<Void> getUnAuthorizedMono(ServerHttpResponse serverHttpResponse){
        serverHttpResponse.getHeaders().add("Content-Type","application/json;charset=UTF-8");
        RespnseResult<Object> respnseResult = RespnseResult.error(ResultCode.UNAUTHORIZED.getMsg());
        DataBuffer dataBuffer = serverHttpResponse.bufferFactory().wrap(JSON.toJSONString(respnseResult).getBytes(StandardCharsets.UTF_8));
        return serverHttpResponse.writeWith(Flux.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
